<template>
  <layout navbar="none" :showBack="false" navbarBackgroundColor="#020303">
    <!-- 使用tn-nav-bar组件 -->
    <tn-nav-bar
      fixed
      alpha
      backgroundColor="#020303"
      :isBack="true"
      fontColor="#FFFFFF"
      @goBack="goBack">
      
      <view class="nav-title">
        积分明细
      </view>
    </tn-nav-bar>

    <view class="points-detail-page" :style="{paddingTop: vuex_status_bar_height + 44 + 'px'}">
      <!-- 积分概览 -->
      <view class="points-overview">
        <view class="overview-bg">
          <view class="bg-decoration">
            <text class="tn-icon-gift decoration-icon1"></text>
            <text class="tn-icon-vip-diamond-fill decoration-icon2"></text>
          </view>
          <view class="overview-content">
            <view class="points-icon">
              <text class="tn-icon-gift main-icon"></text>
            </view>
            <view class="total-points">
              <view class="points-number-container">
                <view class="points-number">{{ currentUserPoints }}</view>
                <view class="points-unit">积分</view>
              </view>
              <view class="points-label">我的积分余额</view>
              <view class="points-desc">可用于社交互动</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 日期筛选按钮 -->
      <view class="date-filter-section">
        <view class="date-filter-btn" @tap="showCalendar" :class="{'active': hasDateFilter}">
          <text class="tn-icon-calendar"></text>
          <text>{{ filterButtonText }}</text>
        </view>
      </view>

      <!-- 筛选标签 -->
      <view class="filter-section">
        <view class="filter-tabs">
          <view 
            class="filter-tab" 
            :class="{'active': activeTab === tab.key}" 
            v-for="tab in filterTabs" 
            :key="tab.key"
            @tap="switchTab(tab.key)"
          >
            {{ tab.label }}
          </view>
        </view>
      </view>

      <!-- 当前筛选条件显示 -->
      <view class="current-filter" v-if="hasDateFilter">
        <view class="filter-info">
          <text class="filter-text">筛选日期：{{ filterButtonText }}</text>
          <view class="clear-filter" @tap="clearFilter">
            <text class="tn-icon-close"></text>
            <text>清除</text>
          </view>
        </view>
      </view>

      <!-- 积分记录列表 -->
      <view class="records-container">
        <view class="records-list" v-if="filteredRecords.length > 0">
          <view class="record-item" v-for="(record, index) in filteredRecords" :key="index">
            <view class="record-left">
              <view class="record-icon" :class="record.type">
                <text :class="record.icon"></text>
              </view>
              <view class="record-info">
                <view class="record-title">{{ record.title }}</view>
                <view class="record-desc">{{ record.desc }}</view>
                <view class="record-time">{{ record.time }}</view>
              </view>
            </view>
            <view class="record-amount" :class="{'positive': record.amount > 0, 'negative': record.amount < 0}">
              {{ record.amount > 0 ? '+' : '' }}{{ record.amount }}
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-else>
          <view class="empty-icon">
            <text class="tn-icon-empty-history"></text>
          </view>
          <view class="empty-text">暂无积分记录</view>
          <view class="empty-desc">快去完成任务赚取积分吧！</view>
        </view>
      </view>

      <!-- 底部安全区域 -->
      <view class="safe-area-bottom"></view>
    </view>
    
    <!-- 日历选择器 -->
    <tn-calendar 
      v-model="showCalendarPicker" 
      mode="range"
      :safe-area-inset-bottom="true"
      active-color="#020303"
      active-bg-color="#B3F73C"
      range-bg-color="rgba(179, 247, 60, 0.1)"
      range-color="#B3F73C"
      btn-color="#B3F73C"
      start-text="开始"
      end-text="结束"
      @change="onCalendarChange"
      @close="onCalendarClose"
    ></tn-calendar>
  </layout>
</template>

<script>
import { mapState } from 'vuex';
import { getPointRecordPage } from '@/api/user/index.js';

export default {
  data() {
    // 获取今天的日期
    const getTodayDate = () => {
      const today = new Date();
      return today.getFullYear() + '-' + 
             String(today.getMonth() + 1).padStart(2, '0') + '-' + 
             String(today.getDate()).padStart(2, '0');
    };
    
    const todayDate = getTodayDate();
    
    return {
      // 筛选状态
      activeTab: 'all',
      showCalendarPicker: false,
      
      // 日期筛选
      startDate: todayDate,
      endDate: todayDate,
      
      // 筛选选项
      filterTabs: [
        { key: 'all', label: '全部' },
        { key: 'earned', label: '获得' },
        { key: 'spent', label: '消耗' }
      ],
      
      // 积分记录数据
      pointsRecords: [],
      
      // 分页数据
      currentPage: 1,
      pageSize: 10,
      totalPages: 0,
      loading: false,
      loadingMore: false,
      noMoreData: false
    }
  },
  onLoad() {
    this.loadPointRecords(true);
  },
  onPullDownRefresh() {
    this.loadPointRecords(true);
  },
  onReachBottom() {
    if (!this.loading && !this.noMoreData) {
      this.loadMoreData();
    }
  },
  computed: {
    ...mapState(['vuex_status_bar_height']),
    ...mapState('user', ['userInfo']),
    
    // 是否有日期筛选
    hasDateFilter() {
      const getTodayDate = () => {
        const today = new Date();
        return today.getFullYear() + '-' + 
               String(today.getMonth() + 1).padStart(2, '0') + '-' + 
               String(today.getDate()).padStart(2, '0');
      };
      
      const todayDate = getTodayDate();
      
      // 如果是默认的今天筛选，不显示筛选条件栏
      if (this.startDate === todayDate && this.endDate === todayDate) {
        return false;
      }
      
      return this.startDate || this.endDate;
    },
    
    // 筛选按钮文字
    filterButtonText() {
      if (this.startDate && this.endDate) {
        if (this.startDate === this.endDate) {
          return this.startDate;
        }
        return `${this.startDate} 至 ${this.endDate}`;
      } else if (this.startDate) {
        return `${this.startDate} 起`;
      } else if (this.endDate) {
        return `至 ${this.endDate}`;
      }
      return '选择日期';
    },
    
    // 当前显示的记录（直接返回API获取的记录）
    filteredRecords() {
      return this.pointsRecords;
    },
    
    // 获取用户当前积分
    currentUserPoints() {
      if (!this.userInfo) return 0;
      return this.userInfo.point || 0;
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 切换筛选标签
    switchTab(tab) {
      if (this.activeTab !== tab) {
        this.activeTab = tab;
        this.loadPointRecords(true);
      }
    },
    
    // 显示日历选择器
    showCalendar() {
      this.showCalendarPicker = true;
    },
    
    // 日历选择变化处理
    onCalendarChange(result) {
      if (result.startDate && result.endDate) {
        this.startDate = result.startDate;
        this.endDate = result.endDate;
        this.showCalendarPicker = false;
        this.loadPointRecords(true);
      }
    },
    
    // 日历关闭处理
    onCalendarClose() {
      this.showCalendarPicker = false;
    },
    
    // 清除筛选条件
    clearFilter() {
      // 重置为今天的日期
      const getTodayDate = () => {
        const today = new Date();
        return today.getFullYear() + '-' + 
               String(today.getMonth() + 1).padStart(2, '0') + '-' + 
               String(today.getDate()).padStart(2, '0');
      };
      
      const todayDate = getTodayDate();
      this.startDate = todayDate;
      this.endDate = todayDate;
      this.loadPointRecords(true);
    },
    
    // 加载积分记录
    async loadPointRecords(refresh = false) {
      if (this.loading) return;
      
      try {
        this.loading = true;
        
        if (refresh) {
          this.currentPage = 1;
          this.pointsRecords = [];
          this.noMoreData = false;
        }
        
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize
        };
        
        // 处理筛选条件
        if (this.activeTab === 'earned') {
          params.addStatus = true;
        } else if (this.activeTab === 'spent') {
          params.addStatus = false;
        }
        
        // 处理日期筛选
        if (this.startDate || this.endDate) {
          if (this.startDate) {
            params['createTime[0]'] = this.startDate + ' 00:00:00';
          }
          if (this.endDate) {
            params['createTime[1]'] = this.endDate + ' 23:59:59';
          }
        }
        
        const response = await getPointRecordPage(params);
        const records = this.convertRecords(response.list || []);
        
        if (refresh) {
          this.pointsRecords = records;
        } else {
          this.pointsRecords.push(...records);
        }
        
        // 计算总页数
        const total = response.total || 0;
        this.totalPages = Math.ceil(total / this.pageSize);
        this.noMoreData = this.currentPage >= this.totalPages;
        
        if (refresh) {
          uni.stopPullDownRefresh();
        }
      } catch (error) {
        console.error('获取积分记录失败:', error);
        
        // 根据错误类型显示不同信息
        let errorMessage = '获取积分记录失败';
        if (error && error.msg) {
          errorMessage = error.msg;
        } else if (error && error.message) {
          errorMessage = error.message;
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none'
        });
      } finally {
        this.loading = false;
        this.loadingMore = false;
      }
    },
    
    // 加载更多数据
    loadMoreData() {
      if (this.noMoreData || this.loading) return;
      
      this.loadingMore = true;
      this.currentPage++;
      this.loadPointRecords(false);
    },
    
    // 转换后端数据格式
    convertRecords(records) {
      return records.map(record => {
        const isPositive = record.point > 0;
        
        return {
          id: record.id,
          title: record.title,
          desc: record.description || '',
          time: this.formatTime(record.createTime),
          amount: record.point,
          type: this.getRecordTypeByTitle(record.title),
          icon: this.getRecordIcon(record.point, record.title),
          category: isPositive ? 'earned' : 'spent'
        };
      });
    },
    
    // 格式化时间显示
    formatTime(createTime) {
      if (!createTime) return '';
      
      // createTime 是毫秒时间戳
      const date = new Date(createTime);
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const recordDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      
      const diffDays = Math.floor((today - recordDate) / (24 * 60 * 60 * 1000));
      const timeStr = date.getHours().toString().padStart(2, '0') + ':' + 
                      date.getMinutes().toString().padStart(2, '0');
      
      if (diffDays === 0) {
        return `今天 ${timeStr}`;
      } else if (diffDays === 1) {
        return `昨天 ${timeStr}`;
      } else if (diffDays <= 7) {
        return `${diffDays}天前`;
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      }
    },
    
    // 根据积分变动获取记录类型
    getRecordType(point) {
      return point > 0 ? 'earned' : 'spent';
    },
    
    // 根据标题获取记录类型（用于样式）
    getRecordTypeByTitle(title) {
      if (title.includes('签到')) {
        return 'signin';
      } else if (title.includes('管理员')) {
        return 'admin';
      } else if (title.includes('订单') || title.includes('购买')) {
        return 'order';
      } else if (title.includes('邀请') || title.includes('分享')) {
        return 'invite';
      } else if (title.includes('任务') || title.includes('完成')) {
        return 'task';
      } else {
        return 'default';
      }
    },
    
    // 根据积分记录获取图标
    getRecordIcon(point, title) {
      // 根据标题判断特定类型的图标
      if (title.includes('签到')) {
        return 'tn-icon-calendar';
      } else if (title.includes('管理员')) {
        return 'tn-icon-vip-diamond-fill';
      } else if (title.includes('订单') || title.includes('购买')) {
        return 'tn-icon-cart-fill';
      } else if (title.includes('邀请') || title.includes('分享')) {
        return 'tn-icon-share';
      } else if (title.includes('任务') || title.includes('完成')) {
        return 'tn-icon-check';
      } else {
        // 默认根据正负数分类
        return point > 0 ? 'tn-icon-gift' : 'tn-icon-cart-fill';
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.points-detail-page {
  min-height: 100vh;
  background-color: #020303;
  color: #e0e0e0;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: radial-gradient(rgba(179, 247, 60, 0.03) 1px, transparent 1px);
    background-size: 30px 30px;
    pointer-events: none;
    z-index: 0;
  }
}

// 导航栏标题样式
.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #e0e0e0;
  text-align: center;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background: linear-gradient(90deg, #8eac21, #B3F73C);
    border-radius: 2rpx;
  }
}

// 积分概览
.points-overview {
  margin: 30rpx;
  position: relative;
  z-index: 1;
  
  .overview-bg {
    background: linear-gradient(135deg, rgba(179, 247, 60, 0.08), rgba(142, 172, 33, 0.08));
    border: 1px solid rgba(179, 247, 60, 0.15);
    border-radius: 24rpx;
    padding: 50rpx 40rpx;
    backdrop-filter: blur(10rpx);
    position: relative;
    overflow: hidden;
    
    // 背景装饰
    .bg-decoration {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      pointer-events: none;
      
      .decoration-icon1 {
        position: absolute;
        top: 30rpx;
        right: 40rpx;
        font-size: 40rpx;
        color: rgba(179, 247, 60, 0.1);
        transform: rotate(15deg);
        animation: float1 3s ease-in-out infinite;
      }
      
      .decoration-icon2 {
        position: absolute;
        bottom: 40rpx;
        left: 50rpx;
        font-size: 30rpx;
        color: rgba(179, 247, 60, 0.08);
        transform: rotate(-10deg);
        animation: float2 4s ease-in-out infinite;
      }
    }
    
    .overview-content {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 40rpx;
      position: relative;
      z-index: 1;
      
      .points-icon {
        .main-icon {
          font-size: 80rpx;
          color: #B3F73C;
          filter: drop-shadow(0 0 20rpx rgba(179, 247, 60, 0.3));
          animation: pulse 2s ease-in-out infinite;
        }
      }
      
      .total-points {
        text-align: left;
        
        .points-number-container {
          display: flex;
          align-items: baseline;
          gap: 10rpx;
          margin-bottom: 15rpx;
          
          .points-number {
            font-size: 72rpx;
            font-weight: 800;
            background: linear-gradient(135deg, #B3F73C, #8eac21);
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
            text-shadow: 0 0 20rpx rgba(179, 247, 60, 0.2);
            animation: numberGlow 3s ease-in-out infinite alternate;
          }
          
          .points-unit {
            font-size: 28rpx;
            color: #B3F73C;
            font-weight: 600;
            opacity: 0.8;
          }
        }
        
        .points-label {
          font-size: 28rpx;
          color: #333;
          font-weight: 600;
          margin-bottom: 8rpx;
        }
        
        .points-desc {
          font-size: 24rpx;
          color: #666;
          opacity: 0.8;
        }
      }
    }
  }
}

// 动画效果
@keyframes float1 {
  0%, 100% {
    transform: translateY(0) rotate(15deg);
  }
  50% {
    transform: translateY(-20rpx) rotate(15deg);
  }
}

@keyframes float2 {
  0%, 100% {
    transform: translateY(0) rotate(-10deg);
  }
  50% {
    transform: translateY(-15rpx) rotate(-10deg);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

@keyframes numberGlow {
  0% {
    filter: drop-shadow(0 0 10rpx rgba(179, 247, 60, 0.2));
  }
  100% {
    filter: drop-shadow(0 0 20rpx rgba(179, 247, 60, 0.4));
  }
}

// 日期筛选区域
.date-filter-section {
  margin: 20rpx 30rpx;
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: flex-start;
  
  .date-filter-btn {
    padding: 16rpx 32rpx;
    background: linear-gradient(135deg, rgba(179, 247, 60, 0.1), rgba(142, 172, 33, 0.1));
    border: 1px solid rgba(179, 247, 60, 0.3);
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    gap: 10rpx;
    color: #B3F73C;
    font-size: 26rpx;
    font-weight: 600;
    transition: all 0.3s;
    
    &:active {
      background: linear-gradient(135deg, rgba(179, 247, 60, 0.2), rgba(142, 172, 33, 0.2));
      transform: scale(0.95);
      border-color: rgba(179, 247, 60, 0.4);
    }
    
    &.active {
      background: linear-gradient(135deg, rgba(179, 247, 60, 0.2), rgba(142, 172, 33, 0.2));
      border-color: rgba(179, 247, 60, 0.5);
      box-shadow: 0 0 25rpx rgba(179, 247, 60, 0.3);
    }
    
    .tn-icon-calendar {
      font-size: 28rpx;
      flex-shrink: 0;
    }
    
    text {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

// 筛选区域
.filter-section {
  margin: 0 30rpx 20rpx;
  position: relative;
  z-index: 1;
  
  .filter-tabs {
    display: flex;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 10rpx;
    padding: 8rpx;
    
    .filter-tab {
      flex: 1;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      border-radius: 8rpx;
      transition: all 0.3s;
      color: #999;
      
      &.active {
        background: linear-gradient(135deg, rgba(179, 247, 60, 0.2), rgba(142, 172, 33, 0.2));
        color: #B3F73C;
        font-weight: 600;
      }
    }
  }
}

// 当前筛选条件显示
.current-filter {
  margin: 0 30rpx 20rpx;
  position: relative;
  z-index: 1;
  
  .filter-info {
    background: linear-gradient(135deg, rgba(179, 247, 60, 0.1), rgba(142, 172, 33, 0.1));
    border: 1px solid rgba(179, 247, 60, 0.3);
    border-radius: 16rpx;
    padding: 20rpx 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .filter-text {
      font-size: 26rpx;
      color: #B3F73C;
      font-weight: 600;
      flex: 1;
    }
    
    .clear-filter {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 12rpx 20rpx;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 20rpx;
      transition: all 0.3s;
      
      &:active {
        background: rgba(255, 255, 255, 0.15);
        transform: scale(0.95);
      }
      
      .tn-icon-close {
        font-size: 20rpx;
        color: #999;
      }
      
      text:last-child {
        font-size: 22rpx;
        color: #999;
      }
    }
  }
}

// 记录容器
.records-container {
  position: relative;
  z-index: 1;
  
  .records-list {
    margin: 0 30rpx;
    
    .record-item {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.08);
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all 0.3s;
      
      &:active {
        transform: scale(0.98);
        background: rgba(255, 255, 255, 0.08);
      }
      
      .record-left {
        display: flex;
        align-items: center;
        flex: 1;
        
        .record-icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 24rpx;
          font-size: 36rpx;
          
          &.signin {
            background: linear-gradient(135deg, rgba(52, 152, 219, 0.2), rgba(41, 128, 185, 0.2));
            color: #3498db;
          }
          
          &.admin {
            background: linear-gradient(135deg, rgba(142, 68, 173, 0.2), rgba(155, 89, 182, 0.2));
            color: #9b59b6;
          }
          
          &.order {
            background: linear-gradient(135deg, rgba(231, 76, 60, 0.2), rgba(192, 57, 43, 0.2));
            color: #e74c3c;
          }
          
          &.invite {
            background: linear-gradient(135deg, rgba(46, 204, 113, 0.2), rgba(39, 174, 96, 0.2));
            color: #2ecc71;
          }
          
          &.task {
            background: linear-gradient(135deg, rgba(241, 196, 15, 0.2), rgba(243, 156, 18, 0.2));
            color: #f1c40f;
          }
          
          &.default {
            background: linear-gradient(135deg, rgba(179, 247, 60, 0.2), rgba(142, 172, 33, 0.2));
            color: #B3F73C;
          }
        }
        
        .record-info {
          flex: 1;
          
          .record-title {
            font-size: 28rpx;
            color: #e0e0e0;
            font-weight: 600;
            margin-bottom: 8rpx;
          }
          
          .record-desc {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 8rpx;
          }
          
          .record-time {
            font-size: 22rpx;
            color: #666;
          }
        }
      }
      
      .record-amount {
        font-size: 32rpx;
        font-weight: 600;
        
        &.positive {
          color: #B3F73C;
        }
        
        &.negative {
          color: #e74c3c;
        }
      }
    }
  }
  
  // 空状态
  .empty-state {
    text-align: center;
    padding: 100rpx 30rpx;
    
    .empty-icon {
      width: 120rpx;
      height: 120rpx;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 30rpx;
      font-size: 60rpx;
      color: #666;
    }
    
    .empty-text {
      font-size: 32rpx;
      color: #999;
      margin-bottom: 10rpx;
    }
    
    .empty-desc {
      font-size: 24rpx;
      color: #666;
    }
  }
}

// 底部安全区域
.safe-area-bottom {
  height: 120rpx;
  background-color: transparent;
}
</style>
